<template>
  <t-modal
    title="前置任务"
    width="1000px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    :wrapClassName="
      'pretask-modal-container ' + (operate == 1 ? '' : 'no-footer')
    "
    forceRender
    v-bind:confirmLoading="confirmLoading"
  >
    <div class="curve-modal-body">
      <div class="operate-warp" v-if="operate == 1">
        <a-button icon="plus" type="primary" @click="handelAddEvent()"
          >新增</a-button
        >
      </div>
      <div class="table-container">
        <vxe-table
          :data="tableData"
          height="99%"
          show-overflow
          :loading="loading"
          ref="xTable"
        >
          <!-- 序号 -->
          <vxe-table-column
            title="序号"
            type="seq"
            width="60"
            align="center"
          ></vxe-table-column>
          <!-- 任务名称 -->
          <vxe-table-column field="labelInValue" title="任务名称" width="350px">
            <template slot-scope="scope">
              <a-tree-select
                v-if="operate == 1"
                v-model="scope.row.labelInValue"
                style="width:320px"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="taskSource"
                :replaceFields="{
                  children: 'childList',
                  title: 'name',
                  key: 'uuid',
                  value: 'uuid',
                }"
                placeholder="请选择"
                :load-data="onLoadData"
                @change="changeTaskEvent($event, scope)"
                labelInValue
              >
              </a-tree-select>
              <span v-else>{{ scope.row.sourceTaskName }}</span>
            </template>
          </vxe-table-column>
          <!-- 类型 -->
          <vxe-table-column field="type" title="类型" width="230px">
            <template slot-scope="scope">
              <a-select
                v-if="operate == 1"
                v-model="scope.row.type"
                style="width:200px"
                placeholder="请选择"
                @change="$refs.xTable.updateStatus(scope)"
              >
                <a-select-option
                  :value="item.value"
                  v-for="(item, index) in typeSource"
                  :key="index"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <span v-else>{{ getTypeName(scope.row.type) }}</span>
            </template>
          </vxe-table-column>
          <!-- 间隔时间(天) -->
          <vxe-column
            field="duration"
            :width="operate == 1 ? '230px' : 'auto'"
            title="间隔时间(天)"
          >
            <template slot-scope="scope">
              <a-input-number
                v-if="operate == 1"
                style="width:200px"
                v-model="scope.row.duration"
                :min="0"
                placeholder="请输入"
                @change="$refs.xTable.updateStatus(scope)"
              />
              <span v-else>{{ scope.row.duration }}</span>
            </template>
          </vxe-column>
          <!-- 操作 -->
          <vxe-column
            field="operate"
            title="操作"
            fixed="right"
            v-if="operate == 1"
          >
            <template slot-scope="scope">
              <div class="text-button-group">
                <a-tooltip>
                  <template slot="title">删除</template>
                  <a-icon
                    type="delete"
                    @click="handleDeleteEvent(scope.row, scope.rowIndex)"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </t-modal>
</template>

<script>
import {
  getConfigDetail,
  getConfigDetailDraft,
  getConfigDetailHistory,
  getTreeListDraft,
  getTreeListDraftChildren,
} from "@/api/progressManage";
import { addAttributeByKey } from "@/utils/util.js";
export default {
  inject: ["moduleSource"],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    //版本信息
    versionInfo: {
      type: Object,
      default: () => {},
    },
    //0查看 1编辑
    operate: {
      type: Number,
      default: 0,
    },

    row: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      loading: false,
      confirmLoading: false,
      tableData: [],
      //任务名称
      taskSource: [],
      //类型
      typeSource: [
        { value: "FS", name: "完成-开始" },
        { value: "SS", name: "开始-开始" },
        { value: "FF", name: "完成-完成" },
        { value: "SF", name: "开始-完成" },
      ],
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
    },
  },
  methods: {
    getConfigDetail,
    getConfigDetailDraft,
    getConfigDetailHistory,

    //类型名称
    getTypeName(type = "") {
      switch (type) {
        case "FS":
          return "完成-开始";

        case "SS":
          return "开始-开始";

        case "FF":
          return "完成-完成";

        case "SF":
          return "开始-完成";

        default:
          break;
      }
    },

    //删除
    handleDeleteEvent(row, index) {
      this.tableData.splice(index, 1);
    },

    //监听选择任务名称
    changeTaskEvent(event, scope) {
      let { label, value } = event;
      let { rowIndex } = scope;
      this.tableData[rowIndex].sourceItemId = value;
      this.tableData[rowIndex].sourceTaskName = label;
      this.$refs.xTable.updateStatus(scope);
    },

    //查询数据
    async getData() {
      //任务名称
      await this.getTaskData();
      //
      this.getDetail();
    },

    //查询任务名称
    getTaskData() {
      let { uuid } = this.versionInfo;
      return new Promise((resolve, reject) => {
        getTreeListDraft({
          proCode: "",
          versionId: uuid,
          orgCode: "",
          nodeType: this.moduleSource(),
        })
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childList"
            );
            this.taskSource = filterData;
            resolve();
          })
          .catch((_) => {
            this.taskSource = [];
            reject();
          });
      });
    },

    //树形数据懒加载
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        const { uuid, childList } = treeNode.dataRef;
        if (!childList || (childList && childList.length == 0)) {
          getTreeListDraftChildren({
            parentId: uuid,
            proCode: "",
            orgCode: "",
            versionId: this.versionInfo.uuid,
          })
            .then((res) => {
              let source = res?.data || [];
              source.forEach((v) => {
                let { isLast } = v;
                v.isLeaf = isLast;
              });
              let filterData = addAttributeByKey(
                null,
                "scopedSlots",
                { icon: "custom" },
                source,
                "childList"
              );
              treeNode.dataRef.childList = filterData;
              this.taskSource = [...this.taskSource];
              setTimeout((_) => {
                resolve();
              }, 200);
            })
            .catch((_) => {});
        } else {
          resolve();
        }
      });
    },

    //新增
    handelAddEvent() {
      this.tableData.push({
        sourceItemId: undefined,
        sourceTaskName: "",
        labelInValue: undefined,
        type: undefined,
        duration: "",
      });
    },

    getDetail() {
      this.loading = true;
      let { status } = this.versionInfo;
      let { uuid } = this.row;
      let apiUrl = "";
      if (status == 4) {
        //正式
        apiUrl = "getConfigDetail";
      } else if (status == 5) {
        //归档
        apiUrl = "getConfigDetailHistory";
      } else {
        //草稿
        apiUrl = "getConfigDetailDraft";
      }
      return new Promise((resolve, reject) => {
        this[apiUrl]({
          uuid,
          proCode: "",
        })
          .then((res) => {
            let { data } = res;
            let source = data?.predecessorList ?? [];
            source.forEach((v) => {
              this.$set(v, "labelInValue", {
                label: v.sourceTaskName,
                value: v.sourceItemId,
              });
            });
            this.tableData = source;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //提交
    onSubmit() {
      let { tableData } = this;
      let errorData = tableData.find(
        (v) =>
          !v.sourceItemId ||
          !v.type ||
          v.duration + "" == "" ||
          v.duration + "" == "null"
      );
      if (tableData.length > 0 && errorData) {
        this.$message.error("数据录入不完整！");
      } else {
        this.$emit("change", tableData);
        this.closeModal();
      }
    },

    //关闭弹窗
    closeModal() {
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.pretask-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 24px;
    overflow: auto;
    .operate-warp {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 16px;
    }
    .table-container {
      height: 293px;
    }
  }
  &.no-footer {
    .curve-modal-body {
      .table-container {
        height: 388px;
      }
    }
    .ant-modal-footer {
      display: none;
    }
  }
}
</style>
